<template>
    <div class="w-[80%] mx-auto bg-gray-100 p-4 rounded-md">
        <a-table :dataSource="config" :pagination="false" :bordered="true">
            <a-table-column title="标题" dataIndex="title" key="title" />
            <a-table-column title="表单" key="form">
                <template #default="{ record }">
                    <a-input v-if="record.input === 'input'" v-model:value="formState[record.name]"
                        :placeholder="'请输入' + record.title" />
                    <a-textarea v-else-if="record.input === 'textarea'" v-model:value="formState[record.name]"
                        :placeholder="'请输入' + record.title" />
                    <a-input-number v-else-if="record.input === 'number'" v-model:value="formState[record.name]"
                        :placeholder="'请输入' + record.title" style="width: 100%" />
                    <a-switch v-else-if="record.input === 'boolean'" v-model:checked="formState[record.name]" />
                    <span v-else>{{ record.value }}</span>
                </template>
            </a-table-column>
            <a-table-column title="描述" dataIndex="desc" key="desc" />
            <a-table-column title="操作" key="action">
                <template #default="{ record }">
                    <a-space>
                        <a-button type="primary" size="small" @click="save(record)">保存</a-button>
                        <a-popconfirm :title="`是否确认删除配置 ${record.title}  删除后无法恢复 可能影响系统正常运行`" @confirm="handleDelete(record)">
                            <a-button type="primary" danger size="small">删除</a-button>
                        </a-popconfirm>
                    </a-space>
                </template>
            </a-table-column>
        </a-table>
    </div>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'
import { saveSystemConfig, deleteSystemConfig } from '@/api/system/system'
const props = defineProps<{
    config: any
}>()
const emit = defineEmits<{
    (e: 'success'): void
}>()
const formState = reactive<Record<string, any>>({})

watch(() => props.config, (val) => {
    if (Array.isArray(val)) {
        val.forEach(item => {
            formState[item.name] = item.value
        })
    }
}, { immediate: true })


const save = async (record: any) => {
    const res = await saveSystemConfig({
        id: record.id,
        group_id: record.group_id,
        value: formState[record.name]
    })
    emit('success')
}

const handleDelete = async (record: any) => {
    const res = await deleteSystemConfig({
        id: record.id,
        group_id: record.group_id
    })
    emit('success')
}

</script>
